package com.tcm.pay.request;

import cn.hutool.core.util.ObjectUtil;
import com.base.core.exception.ServiceException;
import com.base.core.utils.R;
import com.base.social.auth.Auth;
import com.base.social.auth.factory.WechatMiniAuthFactory;
import com.base.social.config.AuthConfig;
import com.base.social.domain.AuthCallbackParams;
import com.base.social.domain.AuthToken;
import com.tcm.pay.enums.BusinessCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class WxMiniAuth{

    private static final Logger logger = LoggerFactory.getLogger(WxMiniAuth.class);

    private Auth wxService;



    public String authOpenId(String code) {

        if(ObjectUtil.isEmpty(code)){
            R.throwFail(BusinessCodeEnum.WECHAT_CODE_NOT_FOUND);
        }
        AuthConfig authConfig = new AuthConfig();
        authConfig.setScope("snsapi_userinfo");
        authConfig.setClientId("wx9d9bf3ce52169f1f");
        authConfig.setClientSecret("2d2327601cb01ce5b9d491abdcfe0cc2");

        this.wxService = WechatMiniAuthFactory.build().instance(authConfig, null);

        try {
            AuthCallbackParams authCallbackParams = new AuthCallbackParams();
            authCallbackParams.setCode(code);
            R res = this.wxService.oauthGetToken(authCallbackParams);
            AuthToken authToken = (AuthToken)res.getData();
            if(ObjectUtil.isNull(authToken)){
                R.throwFail(BusinessCodeEnum.WECHAT_CODE_NOT_FOUND.getCode(),BusinessCodeEnum.WECHAT_CODE_NOT_FOUND.getMessage());
            }
           return authToken.getOpenId();
        } catch (ServiceException e) {
            throw e;
        }
    }

}
